package com.example.kuaizu.controller;


import cn.hutool.core.bean.BeanUtil;
import kuaizu.common.exception.MassageException;
import kuaizu.common.tablepojo.School;
import com.example.kuaizu.pojo.UpdateUserTokenParam;
import com.example.kuaizu.pojo.UserProfile;
import com.example.kuaizu.pojo.ov.UserProfileOv;
import com.example.kuaizu.service.InUserService;
import com.example.kuaizu.utils.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.Valid;
import kuaizu.common.constp.KuaiZuConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.util.List;
import java.util.Map;

import static kuaizu.common.constp.KuaiZuConst.ERROR;

/**
 * @author xiaokai
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private InUserService inUserService;
    @Autowired
    private WxRequestUtils wxRequestUtils;


    //用户注册
    @PostMapping("/region")
    public AjaxResponse getUserRegion(@RequestBody UserProfileOv userOv) throws Exception {
        //用户注册]
        String jsCode = userOv.getJsCode();
        //todo密码校验
        log.info("jsCode:{}", jsCode);
        log.info("用户信息:{}", userOv);
        UserProfile userProfile = new UserProfile();
        //UserProfile userinfo = inUserService.login(jsCode);
        //将字符串转成json对象
        //调用WxRequestUtils.getRequest(jsCode)获取openid
        String json = wxRequestUtils.getRequest(jsCode);
        //将字符串转成json对象
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // 将 JSON 字符串转换为 Map 集合
        Map<String, Object> map = objectMapper.readValue(json, Map.class);
        if (map.get("errcode") != null) {
            if (map.get("errcode").equals(KuaiZuConst.LOGIN_Error_NOJSCODE)) {
                //表示无效的jscode需要重新登陆获取
                System.out.println("无效的jscode");
                throw new Exception("无效的jscode,请重新登陆");
            }
            throw new MassageException(ERROR, "服务异常,重新登陆");
        }
        userOv.setOpenid(map.get("openid").toString());
        BeanUtil.copyProperties(userOv, userProfile);
        log.info("用户信息{}", userProfile);
        int i = inUserService.userRegion(userProfile);
        System.out.println(i);
        //6. 注册失败
        //将对象转成map集合
        ObjectMapper objectMapper2 = new ObjectMapper();
        Map map1 = objectMapper2.convertValue(userOv, Map.class);
        String token = JwtUtils.genToken(map1);
        return AjaxResponse.success("注册成功", token);
    }


    //登陆
    @PostMapping("/login")
    public AjaxResponse login(@RequestBody Map<String,String> pram//登陆获取的code
    ) throws Exception {
        if(pram.get("jsCode") == null){
            return AjaxResponse.error("jsCode不能为空");
        }
        String jsCode = pram.get("jsCode");
        log.info("jsCode:{}", jsCode);
        UserProfile userinfo = inUserService.login(jsCode);
        //将对象转成map集合
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.convertValue(userinfo, Map.class);
        String token = JwtUtils.genToken(map);
        //登陆成功返回提示,将用户信息返回给前端
        return AjaxResponse.success("登录成功", token);
    }

    // 测试
    @PostMapping("/login1/{jsCode}")
    public AjaxResponse login1(@PathVariable String jsCode) throws Exception {
        log.info("jsCode:{}", jsCode);
        UserProfile userinfo = inUserService.login(jsCode);
        //将对象转成map集合
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.convertValue(userinfo, Map.class);
        String token = JwtUtils.genToken(map);
        //登陆成功返回提示,将用户信息返回给前端
        return AjaxResponse.success("登录成功", token);
    }

    //更新个人信息
    @PostMapping("/update")
    public AjaxResponse updateUser(@RequestBody UserProfile user) {
        int i = inUserService.updateUser(user);
        if (i > 0) return AjaxResponse.success("更新成功");
        return AjaxResponse.error("更新失败");
    }

    //上传头像
    @PostMapping("/uploadavatar")
    public AjaxResponse uploadAvatar(MultipartFile file) {
        //上传文件
        String url = inUserService.uploadAvatar(file);
        return AjaxResponse.success("上传成功", url);
    }

    //上穿背景图
    @PostMapping("/uploadbg")
    public AjaxResponse uploadBg(MultipartFile file) {
        //上传文件
        String url = inUserService.uploadBg(file);
        return AjaxResponse.success("上传成功", url);
    }


    //获取用户信息
    @GetMapping("/getuserinfo")
    public AjaxResponse getUserInfo() {
        //获取用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        log.info("用户细腻{}",map);
        UserProfile user = inUserService.selectUserByAppid(map.get("openid").toString());
        return AjaxResponse.success("获取成功", user);
    }

    //添加学校
    @PostMapping("/addschool")
    public AjaxResponse addSchool(String school) {


        return AjaxResponse.success("添加成功");
    }

    //查找学校
    @GetMapping("/school")
    public AjaxResponse getSchool(String school) {
        List<School> schools = inUserService.selectSchool(school);
        log.info("查找对应的学校:{}", school);
        return AjaxResponse.success("查找成功", schools);
    }

    //查找学校
    @PostMapping("/school")
    public AjaxResponse getSchool2(@RequestBody Map<String, Object> paramMap) {
        String s = "";
        if (paramMap.get("name") != null) {
            s = paramMap.get("name").toString();
        }
        List<School> schools = inUserService.selectSchool(s);
        log.info("查找对应的学校:{}", s);
        return AjaxResponse.success("查找成功", schools);
    }

    //更改邮箱
    @PostMapping("/updateemail")
    public AjaxResponse updateEmail(String email) {
        //验证邮箱地址是否争取
        if (!EmailPromotionUtils.isEmailValid(email)) {
            return AjaxResponse.error("邮箱地址不正确");
        }
        //获取用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        UserProfile user = new UserProfile();
        user.setEmail(email);
        user.setOpenid(map.get("openid").toString());
        inUserService.updateUser(user);
        return AjaxResponse.success("更改成功");
    }

    //更改手机号
    @PostMapping("/updatephone")
    public AjaxResponse updateMobile(String phone) {
        //验证手机号是否正确
        String phoneRegex = "^1[3-9]\\d{9}$";
        if (!phone.matches(phoneRegex)) {
            return AjaxResponse.error("手机号不正确");
        }
        //获取用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        UserProfile user = new UserProfile();
        user.setPhone(phone);
        user.setOpenid(map.get("openid").toString());
        inUserService.updateUser(user);
        return AjaxResponse.success("更改成功");
    }

    //上传学生证照片
    @PostMapping("/upstudentimg")
    public AjaxResponse upStudentImg(MultipartFile file) {
        //上传文件
        String url = inUserService.uplStudentImg(file);
        return AjaxResponse.success("上传成功", url);
    }

    //获取手机号
    @PostMapping("/getphone")
    public AjaxResponse getPhone(@RequestBody Map<String, String> map) {
        return inUserService.getPhone( map);

    }


    //更新用户token接口
    @PostMapping("/updateusertoken")
    public AjaxResponse updateUserToken(@Valid @RequestBody UpdateUserTokenParam param ) {
       return AjaxResponse.success(inUserService.updateUserToken(param));

    }


}
